#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import re


class Tool:
    #去除img标签,7位长空格
    removeImg = re.compile('<img.*?>| {7}|')
    #删除超链接标签
    removeAddr = re.compile('<a.*?>|</a>')
    #把换行的标签换为\n
    replaceLine = re.compile('<tr>|<div>|</div>|</p>')
    #将表格制表<td>替换为\t
    replaceTD= re.compile('<td>')
    #把段落开头换为\n加空两格
    replacePara = re.compile('<p.*?>')
    #将换行符或双换行符替换为\n
    replaceBR = re.compile('<br><br>|<br>')
    #将其余标签剔除
    removeExtraTag = re.compile('<.*?>')
    def replace(self,x):
        x = re.sub(self.removeImg,"",x)
        x = re.sub(self.removeAddr,"",x)
        x = re.sub(self.replaceLine,"",x)
        x = re.sub(self.replaceTD,"\t",x)
        x = re.sub(self.replacePara,"",x)
        x = re.sub(self.replaceBR,"",x)
        x = re.sub(self.removeExtraTag,"",x)
        #strip()将前后多余内容删除
        return x.strip()

class DouBan:
    
    def __init__(self,search_word,choice):
        cat = {'1':1005,'2':1019,'3':2012,'4':1001,'5':1002,'6':1003,'7':3114}        
        values = {}
        values['cat'] = cat[choice]
        values['q'] = search_word
        self.data = urllib.urlencode(values)
        self.BaseURL = 'http://www.douban.com/search'
        self.tool = Tool()
    
    #源数据
    def getData(self):
        try:
            URL = self.BaseURL + '?' + self.data
            requset = urllib2.Request(URL)
            response = urllib2.urlopen(requset)
            return response.read().decode('utf-8','ignore')
        except  urllib2.URLError, e:
            if hasattr(e,"reason"):
                print "连接豆瓣失败,错误原因",e.reason
                return None         
    #抓成员
    def analyse01(self):
        data = self.getData()
        parttern = re.compile('<div class="title">.*?<a.*?>(.*?)</a>.*?<div class="info">(.*?)</div>.*?</div>(.*?)</div>',re.S)
        items = re.finditer(parttern,data)
        for item in items:
            if item.group(1):
                print '【名字】： '.decode('utf-8')+self.tool.replace(item.group(1))+'\n'
            if item.group(2):
                print '【简介】： '.decode('utf-8')+self.tool.replace(item.group(2))+'\n'    
            if item.group(3):
                print '【签名】： '.decode('utf-8')+self.tool.replace(item.group(3))+'\n'    
            print "-------------------------------"        
    
    #抓小站，小组
    def analyse02(self):
        data = self.getData()
        parttern = re.compile('<div class="content">.*?<span>(.*?)</span>.*?<a.*?>(.*?)</a>.*?<div class="info">(.*?)</div>',re.S)
        items = re.finditer(parttern,data)
        for item in items:
            if item.group(1):
                print '类别： '.decode('utf-8')+self.tool.replace(item.group(1))+'\n'
            if item.group(2):
                print '名字： '.decode('utf-8')+self.tool.replace(item.group(2))+'\n'    
            if item.group(3):
                print '人数： '.decode('utf-8')+self.tool.replace(item.group(3))+'\n'    
            print "-------------------------------"
    
    #抓书籍，电影，音乐，游戏    
    def analyse03(self):
        data = self.getData()
        parttern = re.compile('<div class="title">.*?<span>(.*?)</span>.*?<a.*?>(.*?)</a>.*?<span class="rating_nums">(.*?)</span>.*?<span>(.*?)</span>.*?<span class="subject-cast">(.*?)</span>',re.S)
        items = re.finditer(parttern,data)
        for item in items:
            if item.group(1):
                print '类别： '.decode('utf-8')+self.tool.replace(item.group(1))+'\n'
            if item.group(2):
                print '名字： '.decode('utf-8')+self.tool.replace(item.group(2))+'\n'
            if item.group(3):
                print '豆瓣评分： '.decode('utf-8')+self.tool.replace(item.group(3))+'\n'
            if item.group(4):
                print '评价人数： '.decode('utf-8')+self.tool.replace(item.group(4))+'\n'
            if item.group(5):
                print '简介： '.decode('utf-8')+self.tool.replace(item.group(5))+'\n'            
            print "-------------------------------"

def Result(search_word,choice):
    Db = DouBan(search_word, choice)
    if choice == '1':
        print '123'
        Db.analyse01()
    elif choice <= 3:
        Db.analyse02()
    else:
        Db.analyse03()
        
while 1 :
    print '1.成员\n2.小组\n3.小站\n4.书籍\n5.电影\n6.音乐\n7.游戏\n'.decode('utf-8')
    choice  = raw_input('想搜啥子？\n'.decode('utf-8'))
    if(choice <= '0' or choice >='8'):
        print '输入错误，我自爆了'.decode('utf-8')
        exit()
    search_word = raw_input('请输入关键词：\n'.decode('utf-8'))
    print '\n\n-------搜索结果如下--------'.decode('utf-8')
    print '---------------------------------'
    Result(search_word, choice);
    choice1  = raw_input('还搜吗？\n0.退出\n  '.decode('utf-8'))
    print '---------------------------------'
    if(choice1 == '0'):
        exit()
    
    